#coding=utf-8

from db_manager import DBManager 
from  config import *
from tool import Tool
import time
import datetime


class Finance(object):
    def __init__(self,cfgParam):

        
        self.cfgParam = cfgParam
        self.manager = DBManager(db,ip,ur,pd)
        self.manager.connect()
        self.tool = Tool()
    def clean(self):
        update_sql1 = "delete from %s " %machine_report
	self.manager.execute(update_sql1)
        update_sql1 = "delete from %s " %store_report
	self.manager.execute(update_sql1)
        update_sql1 = "delete from %s " %user_consume
	self.manager.execute(update_sql1)
        update_sql1 = "delete from %s " %user_recharge
	self.manager.execute(update_sql1)
        update_sql1 = "update %s set all_income = 0" %store_info
	self.manager.execute(update_sql1)
        update_sql1 = "update %s set all_income = 0" %merchant_info
	self.manager.execute(update_sql1)
        update_sql1 = "update %s set all_recharge=0,all_consume = 0" %user_info
	self.manager.execute(update_sql1)
        update_sql1 = "update %s set all_income = 0" %machine_info
	self.manager.execute(update_sql1)
	ret = {"status":1}
        return ret

    def update_finance(self):
        """ 每完成一笔消费或者充值 更新 商户收入 和用户的总消费 """

        #mustkeys = ["uid","mid","money","finance_type","description","order_sn"]
        mustkeys = ["uid","mid","money"]
        ret = self.tool.check_param(mustkeys,self.cfgParam) 
        if not ret["status"]:
            return ret
	try:
	    info = {"order_sn":self.cfgParam["out_trade_no"],"status":1}
	    result = self.manager.smartQuery(user_consume,info)
	    if not result:
	        ret["status"] = 0
	        ret["code_info"] = "out_trade_no or status of non conformity "
                return ret

	except Exception,e:
	    print e 
	    
	order_sn = int(time.time())
        uid   = int(self.cfgParam["uid"])
        mid   = int(self.cfgParam["mid"])

	money = float(self.cfgParam["money"])
	#description = self.cfgParam["description"]
	#finance_type  = int(self.cfgParam["finance_type"])
	try:
	    updatetime = self.cfgParam["updatetime"]
	    updatetime = updatetime.encode("utf-8")
	except Exception,e:

            updatetime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
        updatedate = updatetime.split(" ")[0]
        #if finance_type == 1:
        if 1 == 1:
            #type 1代表套餐消费 更新 用户充值用户消费 所属商户  所属门店 更新商户总收入。 更新门店今日收入
	    relation_info  = {"mid":mid}
	    result = self.manager.smartQuery(machine_relation,relation_info)
	    merchantid = result[0]["merchantid"]
	    storeid    = result[0]["storeid"]

	    #sql -------------
	    #门店报表查询
	    machinereport_qry_info = {"mid":mid,"datetime":updatedate}
	    #门店报表数据添加
	    storereport_insert_info = "insert into %s set storeid = %d,datetime='%s',all_income=%.2f" %(store_report,mid,updatedate,money)
	    #机器报表数据添加
	    machinereport_insert_info = "insert into %s set mid = %d,datetime='%s',all_income=%.2f" %(machine_report,mid,updatedate,money) 
	    #用户充值表数据添加
            #userrecharge_insert_info = {"uid":uid,"recharge_type":finance_type,"mount":money,"recharge_orderid":order_sn,"mid":mid,"recharge_time":updatetime,"recharge_day":updatedate,"recharge_description":description} 
	    #用户消费表数据添加
            #userconsume_insert_info = {"uid":uid,"order_type":finance_type,"mount":money,"order_sn":order_sn,"mid":mid,"pay_time":updatetime,"description":description} 
	    #门店报表数据更新
	    update_storereport  = "update %s set all_income = format(all_income,2) + %.2f  where storeid = %d and datetime = '%s' "%(store_report,money,storeid,updatedate)
	    #机器报表数据更新
	    update_machinereport  = "update %s set all_income = format(all_income,2) + %.2f  where mid = %d and datetime = '%s' "%(machine_report,money,mid,updatedate)
	    #用户详情表数据更新
            #update_userinfo     = "update %s set all_consume = format(all_consume,2) + %.2f ,all_recharge= all_recharge+%d where UID = %d"%(user_info,money,money,uid)
	    #商户详情表数据更新
	    update_merchantinfo = "update %s set all_income = format(all_income,2) + %.2f  where merchantid = %d"%(merchant_info,money,merchantid)
	    #门店详情表数据更新
	    update_storeinfo = "update %s set all_income = format(all_income,2) + %.2f  where storeid = %d"%(store_info,money,storeid)
	    #机器详情表数据更新
	    update_machineinfo = "update %s set ALL_INCOME = format(ALL_INCOME,2) + %.2f  where MachineId = %d"%(machine_info,money,mid)
	    update_consumeinfo = "update {} set status = 2 where order_sn = {}".format(user_consume,self.cfgParam["out_trade_no"]) 
	    #exec sql --------
            #self.manager.smartInsert(user_recharge,userrecharge_insert_info)
            #self.manager.smartInsert(user_consume,userconsume_insert_info)
            qryRet = self.manager.smartQuery(machine_report,machinereport_qry_info)
            if qryRet:
                print qryRet
	        result = self.manager.execute(update_machinereport)
	        result = self.manager.execute(update_storereport)
	    else:
	        result = self.manager.execute(machinereport_insert_info)
	        result = self.manager.execute(storereport_insert_info)

	    #result = self.manager.execute(update_userinfo)
	    result = self.manager.execute(update_merchantinfo)
	    result = self.manager.execute(update_storeinfo)
	    result = self.manager.execute(update_machineinfo)
	    result = self.manager.execute(update_consumeinfo)

            ret['status']=1
        return ret

